'use strict'

const { Controller } = require('egg')

class PermissionsController extends Controller {
  // 添加权限
  async createPermission() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      name: { type: 'string', required: true, desc: '权限名称' },
      class: { type: 'string', required: true, desc: '分组类型' },
      class_name: { type: 'string', required: true, desc: '分组名称' },
      is_parent: { type: 'boolean', required: true, desc: '是否为父级' },
      url: { type: 'string', desc: '接口路径' }
    })
    const { name, class: class_path, class_name, is_parent, url } = ctx.request.body

    // 储存数据库
    await app.model.Permissions.create({
      name,
      class: class_path,
      class_name,
      is_parent,
      url
    })
    ctx.apiSuccess('添加成功')
  }
  // 权限列表
  async getPermissionList() {
    const { ctx, app } = this
    let permissionsList = await app.model.Permissions.findAll({
      attributes: ['id', 'name', 'class', 'is_parent']
    })
    permissionsList = JSON.parse(JSON.stringify(permissionsList))
    // 获取父级
    const permissionsTree = permissionsList.filter((v) => v.is_parent === true)
    // 获取子级
    const getTreeData = (array) => {
      array.forEach((v, i) => {
        const children = permissionsList.filter((v1) => {
          const ls = v1.class.split(':')
          return v.class === ls.splice(0, ls.length - 1).join(':')
        })
        if (children.length > 0) getTreeData(children)
        v.children = children
      })
    }
    getTreeData(permissionsTree)

    ctx.apiSuccess(permissionsTree)
  }
  // 获取角色对应的权限列表
  async getRolePerm() {
    const { ctx, service } = this
    // 参数验证
    ctx.validate({
      id: { type: 'int', required: true, desc: '角色id' }
    })
    const { id } = ctx.request.query
    const res = await service.permissions.getPermissions(id)
    const perms = res[0].permissions.map((item) => item.id)

    ctx.apiSuccess(perms)
  }
}

module.exports = PermissionsController
